/**
 * 数据验证器
 */
import { REGEX } from './config.js'

/**
 * 验证手机号
 * @param {String} phone - 手机号
 * @returns {Boolean} - 是否有效
 */
export const validatePhone = (phone) => {
  if (!phone) return false
  return REGEX.PHONE.test(phone)
}

/**
 * 验证邮箱
 * @param {String} email - 邮箱地址
 * @returns {Boolean} - 是否有效
 */
export const validateEmail = (email) => {
  if (!email) return false
  return REGEX.EMAIL.test(email)
}

/**
 * 验证身份证号
 * @param {String} idCard - 身份证号
 * @returns {Boolean} - 是否有效
 */
export const validateIdCard = (idCard) => {
  if (!idCard) return false
  return REGEX.ID_CARD.test(idCard)
}

/**
 * 验证密码强度
 * @param {String} password - 密码
 * @returns {Object} - 验证结果
 */
export const validatePassword = (password) => {
  const result = {
    valid: false,
    message: '',
    strength: 0 // 0: 弱, 1: 中, 2: 强
  }
  
  if (!password) {
    result.message = '密码不能为空'
    return result
  }
  
  if (password.length < 6) {
    result.message = '密码长度不能少于6位'
    return result
  }
  
  if (password.length > 20) {
    result.message = '密码长度不能超过20位'
    return result
  }
  
  // 检查是否包含字母和数字
  const hasLetter = /[a-zA-Z]/.test(password)
  const hasNumber = /\d/.test(password)
  const hasSpecial = /[@$!%*?&]/.test(password)
  
  if (!hasLetter || !hasNumber) {
    result.message = '密码必须包含字母和数字'
    return result
  }
  
  result.valid = true
  result.message = '密码格式正确'
  
  // 计算密码强度
  let strength = 0
  if (hasLetter) strength++
  if (hasNumber) strength++
  if (hasSpecial) strength++
  if (password.length >= 8) strength++
  
  if (strength <= 2) {
    result.strength = 0 // 弱
  } else if (strength === 3) {
    result.strength = 1 // 中
  } else {
    result.strength = 2 // 强
  }
  
  return result
}

/**
 * 验证用户名
 * @param {String} username - 用户名
 * @returns {Object} - 验证结果
 */
export const validateUsername = (username) => {
  const result = {
    valid: false,
    message: ''
  }
  
  if (!username) {
    result.message = '用户名不能为空'
    return result
  }
  
  if (username.length < 2) {
    result.message = '用户名长度不能少于2位'
    return result
  }
  
  if (username.length > 20) {
    result.message = '用户名长度不能超过20位'
    return result
  }
  
  // 检查是否包含特殊字符（除了中文、字母、数字、下划线）
  if (!/^[\u4e00-\u9fa5a-zA-Z0-9_]+$/.test(username)) {
    result.message = '用户名只能包含中文、字母、数字和下划线'
    return result
  }
  
  result.valid = true
  result.message = '用户名格式正确'
  return result
}

/**
 * 验证真实姓名
 * @param {String} realName - 真实姓名
 * @returns {Object} - 验证结果
 */
export const validateRealName = (realName) => {
  const result = {
    valid: false,
    message: ''
  }
  
  if (!realName) {
    result.message = '姓名不能为空'
    return result
  }
  
  if (realName.length < 2) {
    result.message = '姓名长度不能少于2位'
    return result
  }
  
  if (realName.length > 10) {
    result.message = '姓名长度不能超过10位'
    return result
  }
  
  // 检查是否只包含中文和字母
  if (!/^[\u4e00-\u9fa5a-zA-Z]+$/.test(realName)) {
    result.message = '姓名只能包含中文和字母'
    return result
  }
  
  result.valid = true
  result.message = '姓名格式正确'
  return result
}

/**
 * 验证银行卡号
 * @param {String} cardNo - 银行卡号
 * @returns {Object} - 验证结果
 */
export const validateBankCard = (cardNo) => {
  const result = {
    valid: false,
    message: ''
  }
  
  if (!cardNo) {
    result.message = '银行卡号不能为空'
    return result
  }
  
  // 移除空格
  const cleanCardNo = cardNo.replace(/\s/g, '')
  
  if (!/^\d+$/.test(cleanCardNo)) {
    result.message = '银行卡号只能包含数字'
    return result
  }
  
  if (cleanCardNo.length < 16 || cleanCardNo.length > 19) {
    result.message = '银行卡号长度应为16-19位'
    return result
  }
  
  // Luhn算法验证
  let sum = 0
  let isEven = false
  
  for (let i = cleanCardNo.length - 1; i >= 0; i--) {
    let digit = parseInt(cleanCardNo.charAt(i))
    
    if (isEven) {
      digit *= 2
      if (digit > 9) {
        digit -= 9
      }
    }
    
    sum += digit
    isEven = !isEven
  }
  
  if (sum % 10 !== 0) {
    result.message = '银行卡号格式不正确'
    return result
  }
  
  result.valid = true
  result.message = '银行卡号格式正确'
  return result
}

/**
 * 验证金额
 * @param {String|Number} amount - 金额
 * @param {Object} options - 选项
 * @returns {Object} - 验证结果
 */
export const validateAmount = (amount, options = {}) => {
  const {
    min = 0,
    max = 999999999,
    decimals = 2
  } = options
  
  const result = {
    valid: false,
    message: ''
  }
  
  if (amount === '' || amount === null || amount === undefined) {
    result.message = '金额不能为空'
    return result
  }
  
  const numAmount = parseFloat(amount)
  
  if (isNaN(numAmount)) {
    result.message = '金额格式不正确'
    return result
  }
  
  if (numAmount < min) {
    result.message = `金额不能小于${min}`
    return result
  }
  
  if (numAmount > max) {
    result.message = `金额不能大于${max}`
    return result
  }
  
  // 检查小数位数
  const decimalPart = amount.toString().split('.')[1]
  if (decimalPart && decimalPart.length > decimals) {
    result.message = `金额最多保留${decimals}位小数`
    return result
  }
  
  result.valid = true
  result.message = '金额格式正确'
  return result
}

/**
 * 验证验证码
 * @param {String} code - 验证码
 * @param {Number} length - 验证码长度
 * @returns {Object} - 验证结果
 */
export const validateCode = (code, length = 6) => {
  const result = {
    valid: false,
    message: ''
  }
  
  if (!code) {
    result.message = '验证码不能为空'
    return result
  }
  
  if (code.length !== length) {
    result.message = `验证码长度应为${length}位`
    return result
  }
  
  if (!/^\d+$/.test(code)) {
    result.message = '验证码只能包含数字'
    return result
  }
  
  result.valid = true
  result.message = '验证码格式正确'
  return result
}

/**
 * 验证地址信息
 * @param {Object} address - 地址对象
 * @returns {Object} - 验证结果
 */
export const validateAddress = (address) => {
  const result = {
    valid: false,
    message: '',
    errors: {}
  }
  
  if (!address) {
    result.message = '地址信息不能为空'
    return result
  }
  
  // 验证收货人姓名
  if (!address.name || address.name.trim() === '') {
    result.errors.name = '收货人姓名不能为空'
  } else if (address.name.length > 20) {
    result.errors.name = '收货人姓名不能超过20个字符'
  }
  
  // 验证手机号
  if (!address.phone) {
    result.errors.phone = '手机号不能为空'
  } else if (!validatePhone(address.phone)) {
    result.errors.phone = '手机号格式不正确'
  }
  
  // 验证省市区
  if (!address.province) {
    result.errors.province = '请选择省份'
  }
  if (!address.city) {
    result.errors.city = '请选择城市'
  }
  if (!address.district) {
    result.errors.district = '请选择区县'
  }
  
  // 验证详细地址
  if (!address.detail || address.detail.trim() === '') {
    result.errors.detail = '详细地址不能为空'
  } else if (address.detail.length < 5) {
    result.errors.detail = '详细地址不能少于5个字符'
  } else if (address.detail.length > 100) {
    result.errors.detail = '详细地址不能超过100个字符'
  }
  
  // 检查是否有错误
  const hasErrors = Object.keys(result.errors).length > 0
  if (hasErrors) {
    result.message = '地址信息填写不完整或格式不正确'
  } else {
    result.valid = true
    result.message = '地址信息验证通过'
  }
  
  return result
}

/**
 * 通用表单验证器
 * @param {Object} data - 表单数据
 * @param {Object} rules - 验证规则
 * @returns {Object} - 验证结果
 */
export const validateForm = (data, rules) => {
  const result = {
    valid: true,
    message: '',
    errors: {}
  }
  
  for (const field in rules) {
    const rule = rules[field]
    const value = data[field]
    
    // 必填验证
    if (rule.required && (value === undefined || value === null || value === '')) {
      result.errors[field] = rule.message || `${field}不能为空`
      continue
    }
    
    // 如果不是必填且值为空，跳过其他验证
    if (!rule.required && (value === undefined || value === null || value === '')) {
      continue
    }
    
    // 长度验证
    if (rule.minLength && value.length < rule.minLength) {
      result.errors[field] = `${field}长度不能少于${rule.minLength}位`
      continue
    }
    
    if (rule.maxLength && value.length > rule.maxLength) {
      result.errors[field] = `${field}长度不能超过${rule.maxLength}位`
      continue
    }
    
    // 正则验证
    if (rule.pattern && !rule.pattern.test(value)) {
      result.errors[field] = rule.message || `${field}格式不正确`
      continue
    }
    
    // 自定义验证函数
    if (rule.validator && typeof rule.validator === 'function') {
      const validateResult = rule.validator(value)
      if (!validateResult.valid) {
        result.errors[field] = validateResult.message
        continue
      }
    }
  }
  
  // 检查是否有错误
  const hasErrors = Object.keys(result.errors).length > 0
  if (hasErrors) {
    result.valid = false
    result.message = '表单验证失败'
  } else {
    result.message = '表单验证通过'
  }
  
  return result
}

export default {
  validatePhone,
  validateEmail,
  validateIdCard,
  validatePassword,
  validateUsername,
  validateRealName,
  validateBankCard,
  validateAmount,
  validateCode,
  validateAddress,
  validateForm
}